package com.xzakota.minesweeper.widget.menu;

import com.xzakota.minesweeper.controller.Game;
import com.xzakota.minesweeper.model.GameModel;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

/**
 * 多人游戏菜单
 *
 * @author Xzakota
 */
public class MultiPlayerGameMenuBar extends JMenuBar implements ActionListener {
    public MultiPlayerGameMenuBar(GameModel model) {
        createGameMenu(model);
        allMenuItemAddListener();
    }

    private void allMenuItemAddListener() {
        Component[] menus = this.getComponents();
        JMenu menu;
        Component[] menuItems;
        for (Component component : menus) {
            menu = (JMenu) component;
            menuItems = menu.getMenuComponents();
            for (Component menuItem : menuItems) {
                if (menuItem instanceof JMenuItem) {
                    ((JMenuItem) menuItem).addActionListener(this);
                }
            }
        }
    }

    private void createGameMenu(GameModel config) {
        JMenu gameMenu = new JMenu("游戏(G)");
        gameMenu.setMnemonic('G');
        add(gameMenu);

        JMenuItem newGameMI = new JMenuItem("开局(N)", 'N');
        newGameMI.setAccelerator(KeyStroke.getKeyStroke("F2"));
        newGameMI.setActionCommand("newGame");
        gameMenu.add(newGameMI);

        gameMenu.addSeparator();

        JMenuItem toggleQuestionFlagMI = new JCheckBoxMenuItem("标记(?)(M)");
        toggleQuestionFlagMI.setMnemonic('M');
        toggleQuestionFlagMI.setActionCommand("toggleQuestionMarkEnable");
        toggleQuestionFlagMI.setSelected(config.isQuestionMarkEnable());
        gameMenu.add(toggleQuestionFlagMI);

        JMenuItem toggleSoundMI = new JCheckBoxMenuItem("声音(S)");
        toggleSoundMI.setMnemonic('S');
        toggleSoundMI.setActionCommand("toggleSoundEnable");
        toggleSoundMI.setSelected(config.isSoundEnable());
        gameMenu.add(toggleSoundMI);

        gameMenu.addSeparator();

        JMenuItem exitMI = new JMenuItem("退出(X)", 'X');
        exitMI.setActionCommand("exitingGame");
        gameMenu.add(exitMI);
    }

    @Override
    public void actionPerformed(ActionEvent event) {
        Game.dispatchEvent(event.getActionCommand());
    }
}
